package com.csc.queue;

import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @description:
 * @author: ChenShuCheng
 * @create: 2021-07-04 19:43
 **/
public class Broker {

    public static List<String> getTopics() {
        Iterator<String> iterator = Topics.topics.keySet().iterator();
        List<String> topicsName = new ArrayList<>();
        while (iterator.hasNext()){
            topicsName.add(iterator.next());
        }
        return topicsName;
    }


    public static String readMsg(String key){
        if (Topics.topics.containsKey(key)) {
            Queue<String> queue = Topics.topics.get(key);
            return queue.poll();
        }
        return null;
    }

    public static List<String> readMsgFromList(String key){
        if (Topics.topicsCopis.containsKey(key)) {
            List<String> list = Topics.topicsCopis.get(key);
            return list;
        }

        return null;
    }

    public static void setTopic(String key,String msg){
        if (Topics.topics.containsKey(key)) {
            Queue<String> queue = Topics.topics.get(key);
            queue.add(msg);
            copyQueue2List(key,msg);
        }else {
            Queue<String> queue = new LinkedBlockingDeque<>();
            queue.add(msg);
            Topics.topics.put(key,queue);
            copyQueue2List(key,msg);
        }
    }

    public static void setTopic(String key) throws Exception {
        if (!Topics.topics.containsKey(key)){
            Topics.topics.put(key,new LinkedBlockingDeque<>());
        }else {
            throw new Exception("已有相同的topic");
        }
    }

    private static void copyQueue2List(String key){
            Queue<String> queue = Topics.topics.get(key);
            List<String> list = new ArrayList<>(queue);
            Topics.topicsCopis.put(key,list);
    }

    private static void copyQueue2List(String key, String content){
        if (!Topics.topicsCopis.containsKey(key)){
            copyQueue2List(key);
        }else {
            List<String> list = Topics.topicsCopis.get(key);
            list.add(content);
        }

    }

    private static class Topics{
        private static final Map<String, Queue<String>> topics = new HashMap<>();
        private static final Map<String,List<String>> topicsCopis = new HashMap<>();
    }
}
